<template>
  <section>
    <template v-if="hasAuth">
      <div class="filter-container">
        <el-select class="w100" size="mini" v-model="listQuery.hasMake" placeholder="是否派卡" clearable>
          <el-option label="是" value="1"></el-option>
          <el-option label="否" value="2"></el-option>
        </el-select>
        <el-select class="w100 ml10" size="mini" v-model="listQuery.hasBind" placeholder="是否开卡" clearable>
          <el-option label="是" value="1"></el-option>
          <el-option label="否" value="2"></el-option>
        </el-select>
        <el-select class="w100 ml10" size="mini" v-model="listQuery.status" placeholder="卡状态" clearable>
          <el-option label="启用" value="1"></el-option>
          <el-option label="禁用" value="2"></el-option>
        </el-select>
        <common-input @keyup.enter.native="handleFilter" class="w200 ml10" placeholder="卡号"
          v-model="listQuery.keyword" />
        <common-input @keyup.enter.native="handleFilter" class="w200 ml10" placeholder="起始卡号段"
          v-model="listQuery.startNo" />
        <common-input @keyup.enter.native="handleFilter" class="w200 ml10" placeholder="结束卡号段"
          v-model="listQuery.endNo" />

        <el-button size="mini" class="ml10" type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
        <el-button class="ml10" size="mini" type="primary" @click="exportExcel">导出</el-button>
        <el-button size="mini" class="ml10" @click="handleCreate" type="primary" icon="el-icon-plus">创建</el-button>
        <el-button size="mini" class="ml10" @click="handleMake" type="primary">派卡</el-button>
      </div>

      <el-alert v-if="ids && ids.length > 0" show-icon>
        <template slot="title">
          <span>已选择 {{ ids.length }} 项</span> <el-button @click="clear()" type="text">清空</el-button>
          <template>
            <el-button @click="enable()" type="text">批量启用</el-button>
            <el-button @click="disable()" type="text">批量禁用</el-button>
            <el-button @click="del()" type="text">批量删除</el-button>
          </template>
        </template>
      </el-alert>
      <el-table ref="dataTable" :height="tableHeight" :data="list" @sort-change="tblSort"
        @selection-change="selectChange" style="width: 100%">
        <el-table-column fixed type="selection" width="55">
        </el-table-column>
        <el-table-column align="left" label="卡号ID" width="180">
          <template slot-scope="scope">
            <span>{{ scope.row.id }}</span>
          </template>
        </el-table-column>
        <el-table-column align="left" label="会员卡号" width="150">
          <template slot-scope="scope">
            <span>{{ scope.row.cardNumber }}</span>
          </template>
        </el-table-column>
        <el-table-column align="left" label="卡密" width="100">
          <template slot-scope="scope">
            <span>{{ scope.row.cardPass }}</span>
          </template>
        </el-table-column>
        <el-table-column align="right" label="卡券金额" width="100">
          <template slot-scope="scope">
            <span>{{ scope.row.price }}</span>
          </template>
        </el-table-column>
        <el-table-column align="left" label="充卡事件" width="100">
          <template slot-scope="scope">
            <span>
              {{ scope.row.type == 1 ? '店铺激活卡' : '红包' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column align="left" label="创卡事件" width="100">
          <template slot-scope="scope">
            <span>{{ scope.row.type == 1 ? '店铺激活卡' : '红包' }}</span>
          </template>
        </el-table-column>
        <el-table-column align="left" label="事件说明" width="180">
          <template slot-scope="scope">
            <span>{{ scope.row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="创卡时间" width="150">
          <template slot-scope="scope">
            <span>{{ scope.row.createdAt }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="是否派卡" width="100">
          <template slot-scope="scope">
            <el-tag :type="getMakeColor(scope.row)">{{ scope.row.hasMakeText }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="left" label="派卡用户" width="180">
          <template slot-scope="scope">
            <span v-if="scope.row.bindOrderId > 0">{{ scope.row.agentName }}<template v-if="scope.row.agentMobile">（{{
              scope.row.agentMobile }}）</template></span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="派卡时间" width="150">
          <template slot-scope="scope">
            <span>{{ scope.row.agentAt }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="是否开卡" width="100">
          <template slot-scope="scope">
            <el-tag :type="getBindColor(scope.row)">{{ scope.row.hasBindText }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="left" label="开卡用户" width="180">
          <template slot-scope="scope">
            <span v-if="scope.row.uid > 0">{{ scope.row.bindName }}（{{ scope.row.bindMobile }}）</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="开卡时间" width="150">
          <template slot-scope="scope">
            <span>{{ scope.row.bindAt }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="是否禁用" width="100">
          <template slot-scope="scope">
            <el-tag :type="getStatusColor(scope.row)">{{ scope.row.statusText }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" fixed="right" v-if="!isSelect" width="200">
          <template slot-scope="scope">
            <span>
              <el-button slot="reference" size="mini" class="qrBtn" type="danager"
                @click="handleQr(scope.row)">物料二维码</el-button>
              <el-dropdown class="ml10">
                <el-button type="text">
                  更多<i class="el-icon-arrow-down el-icon--right"></i>
                </el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item v-if="scope.row.status == 1"
                    @click.native="handleDisable(scope.row)">禁用</el-dropdown-item>
                  <el-dropdown-item v-else @click.native="handleEnable(scope.row)">启用</el-dropdown-item>
                  <el-dropdown-item v-if="scope.row.canDelete == 1"
                    @click.native="handleDelete(scope.row)">删除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </span>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page.sync="listQuery.pageNum" :page-sizes="[20, 30, 50]" :page-size="listQuery.pageSize"
          layout="total, sizes, prev, pager, next, jumper" :total="total"> </el-pagination>
      </div>

      <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false"
        width="900px">
        <el-form :model="form" :rules="rules" ref="form" label-width="150px">
          <el-form-item label="卡类型">
            <template v-if="type == 1">
              实体卡（代号：01）
            </template>
            <template v-else-if="type == 2">
              电子卡（代号：02）
            </template>
          </el-form-item>
          <el-form-item label="创卡批次号/版本">
            <el-select size="mini" class="w100" placeholder="批次号" clearable v-model="cardNoForm.pici"
              @change="getCardNo">
              <el-option v-for="item in batchList" :key="item.id" :label="item.text" :value="item.id"></el-option>
            </el-select>
            <el-select size="mini" class="w100 ml10" placeholder="版本号" clearable v-model="cardNoForm.version"
              @change="getCardNo">
              <el-option v-for="item in batchList" :key="item.id" :label="item.text" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="起始卡号" prop="startNo">
            <common-input v-model="form.startNo" disabled />
          </el-form-item>
          <el-form-item label="创卡数量" prop="num">
            <common-input v-model="form.num" class="w60" maxlength="4" /> 张
          </el-form-item>
          <el-form-item label="卡券金额" prop="price">
            <common-input v-model="form.price" class="w60" maxlength="4" /> 元/张
          </el-form-item>
          <el-form-item label="充卡事件" prop="rewardType">
            <el-radio-group v-model="form.rewardType">
              <el-radio :label="0" v-if="type == 0">红包</el-radio>
              <el-radio :label="1" v-else>店铺激活卡</el-radio>
              <!-- <el-radio :label="1">福利</el-radio>
                    <el-radio :label="2">合伙人</el-radio> -->
            </el-radio-group>
          </el-form-item>
          <el-form-item label="合伙人天数" prop="rewardMemberDays" v-if="form.rewardType == 2">
            <common-input v-model="form.rewardMemberDays" class="w60" maxlength="4" /> 天
          </el-form-item>
          <el-form-item label="创卡事件" prop="eventId">
            <el-select size="mini" class="w100" placeholder="创卡事件" clearable v-model="form.eventId">
              <el-option label="平台福利" value="1"></el-option>
              <el-option label="客户购买" value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="事件说明" prop="description">
            <common-input type="textarea" :autosize="{ minRows: 3, maxRows: 5 }" v-model="form.description" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button size="mini" @click="dialogFormVisible = false">取消</el-button>
          <el-button size="mini" v-if="dialogStatus == 'create'" type="primary" @click="create('form')">确定</el-button>
          <el-button size="mini" v-else type="primary" @click="update('form')">确定</el-button>
        </div>
      </el-dialog>

      <el-dialog title="派卡" :visible.sync="dialogMakeVisible" :close-on-click-modal="false" width="900px">
        <el-form :model="cardMakeForm" :rules="cardRules" ref="cardMakeForm" label-width="150px">
          <el-form-item label="选择派卡用户">
            <el-button type="primary" size="mini" @click="selectAgent()">选择</el-button>
            <template v-if="cardMakeForm.uid === 0 || cardMakeForm.uid > 0">
              {{ cardMakeForm.name }}<template v-if="cardMakeForm.mobile">（{{ cardMakeForm.mobile }}）</template>
            </template>
          </el-form-item>
          <el-form-item label="选择卡号段">
            <common-input class="w200 ml10" placeholder="开始卡号段" v-model="cardMakeForm.startNo" />
            <common-input class="w200 ml10" placeholder="结束卡号段" v-model="cardMakeForm.endNo" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button size="mini" @click="dialogMakeVisible = false">取消</el-button>
          <el-button size="mini" type="primary" @click="make('cardMakeForm')">确定</el-button>
        </div>
      </el-dialog>
      <el-dialog title="选择合伙人" :visible.sync="dialogMemberVisible" :close-on-click-modal="false" width="900px">
        <member-list :formData.sync="memberForm" @okSelect="okSelectMember" />
        <div slot="footer" class="dialog-footer">
          <el-button size="mini" type="primary" @click="dialogMemberVisible = false">关闭</el-button>
        </div>
      </el-dialog>
      <!-- <el-dialog title="物料二维码" :visible.sync="dialogQrVisible" :close-on-click-modal="false" width="600px">

        <div slot="footer" class="dialog-footer">
            <el-button size="mini" type="primary" @click="dialogQrVisible=false">关闭</el-button>
        </div>
    </el-dialog> -->
      <!-- <div class="qrcode" v-show="dialogQrVisible">
            <canvas id="qrcode"></canvas>
            <div class="solid solid1"></div>
            <div class="solid solid2"></div>
            <div class="solid solid3"></div>
            <div class="solid solid4"></div>
            <div class="qrcode-title">物料二维码</div>
        </div> -->
    </template>

    <template v-else>
      <el-row :gutter="20">
        <el-col :span="16">
          <el-form :model="loginForm" :rules="loginRules" ref="loginForm" label-width="200px">
            <el-form-item label="使用密码：" prop="password">
              <el-input size="mini" style="width:200px;" v-model="loginForm.password" placeholder="" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" size="mini" @click="login()">登录</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </template>
  </section>
</template>

<script>
import QRCode from 'qrcode'
import {
  isIntegerNotMust
} from '../../utils/validator'
import {
  cardExport,
  cardPage,
  getCardNo,
  addCard,
  enableCard,
  disableCard,
  deleteCard,
  makeCard,
  loginCard
} from '../../api/card';
import Viewer from 'viewerjs';
import 'viewerjs/dist/viewer.css';
export default {
  components: {
    'member-list': () => import('../../components/Member/index'),
  },
  props: {
    formData: Object,
    type: {
      default: 1,
      type: Number,
    }
  },
  data() {
    return {
      loginForm: {
        password: undefined,
      },
      loginRules: {
        password: [
          {
            required: true,
            message: '请填写使用密码',
            trigger: 'blur'
          }
        ],
      },
      dialogQrVisible: false,
      qrCodeUrl: undefined,
      memberForm: {
        is_select: true,
        is_agent: true,
      },
      dialogMemberVisible: false,
      dialogMakeVisible: false,
      cardMakeForm: {
        uid: undefined,
        startNo: undefined,
        endNo: undefined,
      },
      cardRules: {
      },
      ids: [],
      catList: [],
      rules: {
        startNo: [
          {
            required: true,
            message: '请选择批次/版本生成起始卡号',
            trigger: 'blur'
          }
        ],
        num: [
          {
            required: true,
            message: '创卡数量必填',
            trigger: 'blur'
          }
        ],
        price: [
          {
            required: true,
            message: '红包金额必填',
            trigger: 'blur'
          }
        ],
        eventId: [
          {
            required: true,
            message: '请选择创卡事件',
            trigger: 'blur'
          }
        ],
        description: [
          {
            required: true,
            message: '请填写创卡事件说明',
            trigger: 'blur'
          }
        ],
      },
      cardNoForm: {
        type: 0,
        pici: undefined,
        version: undefined,
      },
      form: {
        type: this.type,
        startNo: undefined,
        num: undefined,
        price: undefined,
        eventId: undefined,
        description: undefined,
        rewardType: this.type,
        rewardMemberDays: undefined,
      },
      dialogStatus: '',
      dialogFormVisible: false,
      textMap: {
        create: '创卡'
      },

      isSelect: false,
      viewerId: null,
      orderLoading: false,
      tableHeight: 200,
      list: null,
      listLoading: true,
      listQuery: {
        pageNum: this.$route.query.pageNum || 1,
        pageSize: this.$route.query.pageSize || 20,
        orderCol: "",
        orderAsc: "",
        type: 0,
        hasBind: undefined,
        hasMake: undefined,
        status: undefined,
        startNo: undefined,
        endNo: undefined,
        keyword: undefined,
      },
      total: null,
      activeName: '1',
      currentId: 0,
      checkLoading: false,
      cids: [],
      batchList: [],
      hasAuth: false,
      sessionKey: "cardSession"
    }
  },
  watch: {
    formData: {
      immediate: true,
      handler(val) {
        this.isSelect = val.is_select;

        // console.log(val)
      }
    }
  },
  mounted() {
    const that = this

    window.onresize = () => {

      return (() => {

        that._getTableHeight()

      })()
    }
  },
  created() {
    this.batchList = [];
    for (let i = 1; i <= 99; i++) {
      let s = i < 10 ? "0" + i : i;
      this.batchList.push({
        id: s,
        name: s,
      });
    }
    this._getTableHeight();

    let pwd = sessionStorage.getItem(this.sessionKey);
    if (pwd && pwd.length > 0) {
      this.doLogin(pwd);
    }

    // this.getList();
  },
  methods: {
    doLogin(pwd) {
      loginCard(
        {
          password: pwd
        }
      ).then((res) => {
        if (res.data == "1") {
          this.hasAuth = true;
          sessionStorage.setItem(this.sessionKey, pwd)

          this.getList();
        } else {
          this.hasAuth = false;
          this.$message.error("密码不正确");
          sessionStorage.setItem(this.sessionKey, "")
        }
      }).catch((err) => {
        this.hasAuth = false;
        sessionStorage.setItem(this.sessionKey, "")
      })
    },
    login() {
      const set = this.$refs;

      set["loginForm"].validate(valid => {
        if (valid) {
          this.doLogin(this.loginForm.password)
        } else {
          return false;
        }
      });
    },
    handleQr(row) {

      let { href } = this.$router.resolve({ path: '/qr?url=' + encodeURIComponent(row.qrUrl) });
      window.open(href, '_blank');

      // let qrcode = document.getElementById('qrcode')
      // QRCode.toCanvas(qrcode, row.qrUrl, { margin: 3 }, (error)=>{
      //     if (error) {
      //         this.$message.success("生成二维码失败");
      //     }
      //     this.dialogQrVisible = true;

      // })
    },
    getStatusColor(row) {
      if (row.status === 1) {
        return "success"
      }

      return "danger"
    },
    getMakeColor(row) {
      if (row.bindOrderId > 0) {
        return "success"
      }

      return "danger"
    },
    getBindColor(row) {
      if (row.uid > 0) {
        return "success"
      }

      return "danger"
    },
    selectChange(selection) {
      this.ids = [];
      if (selection && selection.length > 0) {
        selection.forEach((item) => {
          this.ids.push(item.id)
        })
      }
      // console.log(this.ids)
    },
    handleEnable(row) {
      this.enable([row.id]);
    },
    handleDisable(row) {
      this.disable([row.id]);
    },
    handleDelete(row) {
      this.del([row.id]);
    },
    disable(ids) {
      if (!ids || ids.length < 1) {
        ids = this.ids;
      }
      this.$confirm('确定禁用?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          disableCard({
            ids: ids
          })
            .then(() => {
              this.$message.success("卡禁用成功");
              this.getList();
            });
        }).catch(() => { });
    },
    enable(ids) {
      if (!ids || ids.length < 1) {
        ids = this.ids;
      }
      this.$confirm('确定启用?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          enableCard({
            ids: ids
          })
            .then(() => {
              this.$message.success("卡启用成功");
              this.getList();
            });
        }).catch(() => { });
    },
    del(ids) {
      if (!ids || ids.length < 1) {
        ids = this.ids;
      }
      this.$confirm('确定删除（未派卡的才可删除）?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteCard({
            ids: ids
          })
            .then(() => {
              this.$message.success("卡删除成功");
              this.getList();
            });
        }).catch(() => { });
    },
    getCardNo() {
      if (this.cardNoForm.pici && this.cardNoForm.version) {
        this.cardNoForm.type = this.type == 2 ? 1 : 0;
        getCardNo(this.cardNoForm).then((res) => {
          this.form.startNo = res.data.number;
        }).catch((err) => {
          this.form.startNo = undefined;
        })
      } else {
        this.form.startNo = undefined;
      }
    },
    okSelectProduct(result) {
      this.dialogProductVisible = false;
      if (!this.form.items) {
        this.form.items = [];
      }
      // console.log("idx: " + this.selectedIdx)
      if (typeof this.selectedIdx != "undefined") {
        this.form.items[this.selectedIdx].title = result.title;
        this.form.items[this.selectedIdx].attribute = result.attribute;
        this.form.items[this.selectedIdx].productId = result.productId;
        this.form.items[this.selectedIdx].skuId = result.skuId;
        this.form.items[this.selectedIdx].price = result.price;
        this.form.items[this.selectedIdx].skuInventory = result.skuInventory;
      } else {
        this.form.items.push(result);
      }
      console.log(result)
      // product_add_to_page(
      //     {
      //         pageId: this.pageId,
      //         ids: ids
      //     }
      // ).then((res)=>{
      //     this.$message.success("商品已加入专区");
      //     this.getList();
      //     this.dialogProductVisible = false;
      // }).catch((err)=>{

      // })
      // console.log(ids)
    },
    addItem(idx) {
      this.selectedIdx = idx;
      this.dialogProductVisible = true;
    },
    removeItem(idx) {
      this.$confirm('确定删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          let final_items = [];
          this.form.items.forEach((item, i) => {
            if (i != idx) {
              final_items.push(item);
            }
          })

          this.form.items = final_items;
        }).catch(() => { });
    },
    handleCreate() {
      this.resetTemp();
      this.dialogStatus = 'create';
      this.dialogFormVisible = true;
    },
    create(formName) {
      const set = this.$refs;

      set[formName].validate(valid => {
        if (valid) {
          addCard(this.form)
            .then(() => {
              this.dialogFormVisible = false;
              this.getList();
              this.$message.success("操作已执行");
            })
        } else {
          return false;
        }
      });
    },
    update(formName) {
      const set = this.$refs;
      set[formName].validate(valid => {
        if (valid) {
          if (!this.form.orderNum) {
            this.form.orderNum = 0;
          }
          this.form.cids = [];
          if (this.cids && this.cids.length > 0) {
            this.cids.forEach((item) => {
              this.form.cids.push(item[0]);
            })
          }

          retail_brand_save(this.form).then(() => {
            this.dialogFormVisible = false;
            this.getList();
            this.$message.success("品牌更新成功");
          });
        } else {
          return false;
        }
      });
    },
    resetTemp() {
      this.form = {
        type: this.type,
        startNo: undefined,
        num: undefined,
        price: undefined,
        eventId: undefined,
        description: undefined,
        rewardType: 0,
        rewardMemberDays: undefined,
      };
      this.cardNoForm = {
        pici: undefined,
        version: undefined,
        type: 0,
      };

      this.cids = [];
    },
    _getTableHeight() {
      this.tableHeight = window.innerHeight - 250
    },
    getList() {
      this.listQuery.type = this.type;
      this.listLoading = true;
      cardPage(this.listQuery).then(response => {
        this.list = response.data.list;
        if (!this.list) {
          this.list = [];
        }
        this.total = response.data.total;
        this.listLoading = false;
      })
    },
    viewPic(row) {
      if (row.picture) {
        let all_pic = row.picture.split(",");
        $("#pic_viewer").html("");
        if (all_pic && all_pic.length > 0) {
          all_pic.forEach((item, idx) => {
            var str = '<li style="width:100%;">';
            str += '<img rel-src="' + item + '" src="' + item + '">';
            str += '</li>';
            $("#pic_viewer").append(str);
          })
        }
        this.viewerId && this.viewerId.destroy()
        this.viewerId = new Viewer(document.getElementById('pic_viewer'));
        $('#pic_viewer').find("img").eq(0).trigger("click")
      }
    },
    handleFilter() {
      this.listQuery.pageNum = 1;
      this.getList();
    },
    handleSizeChange(val) {
      this.listQuery.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.pageNum = val;
      this.getList();
    },
    handleUpdate(row) {
      retail_brand_detail(row.id)
        .then(response => {
          this.form = response.data;
          this.cids = [];
          if (this.form.cids && this.form.cids.length > 0) {
            this.form.cids.forEach((item) => {
              this.cids.push([item]);
            })
          }
          this.dialogFormVisible = true;
          this.dialogStatus = 'update';
        });
    },
    dialogClose() {
      this.$refs.form.resetFields();
    },
    tblSort(d) {
      this.listQuery.orderCol = d.prop;
      this.listQuery.orderAsc = d.order;

      this.handleFilter();
    },
    clear() {
      this.$refs.dataTable.clearSelection();
    },
    select() {
      this.$emit('okSelect', this.ids);
    },
    make(formName) {
      const set = this.$refs;

      set[formName].validate(valid => {
        if (valid) {
          if (this.cardMakeForm.uid === 0 || this.cardMakeForm.uid > 0) {
            makeCard(this.cardMakeForm).then((res) => {
              this.dialogMakeVisible = false;
              this.$message.success("指定卡段已派卡");
              this.getList();
            }).catch((err) => {

            })
          } else {
            this.$message.error("请选择派卡用户");
          }
        } else {
          return false;
        }
      });
    },
    handleMake() {
      this.cardMakeForm = {
        uid: undefined,
        startNo: undefined,
        endNo: undefined,
      };

      this.dialogMakeVisible = true;
    },
    selectAgent() {
      this.dialogMemberVisible = true;
    },
    okSelectMember(item) {
      if (item.roleId == 0) {
        this.$message.error("只能选择合伙人");
      } else {
        this.cardMakeForm.uid = item.id;
        this.cardMakeForm.mobile = item.mobile;
        this.cardMakeForm.name = item.nickName;
        this.dialogMemberVisible = false;
      }
      // console.log(item)
    },
    createCellPos(n) {
      var ordA = 'A'.charCodeAt(0);

      var ordZ = 'Z'.charCodeAt(0);

      var len = ordZ - ordA + 1;

      var s = "";



      while (n >= 0) {

        s = String.fromCharCode(n % len + ordA) + s;

        n = Math.floor(n / len) - 1;

      }

      return s;

    },
    exportExcel() {
      this.listQuery.type = this.type;
      cardExport(this.listQuery).then((res) => {
        if (res.data.items && res.data.items.length > 0) {
          let items = res.data.items;

          let export_config = res.data.exportConfig;
          items.unshift(export_config.header)

          var column = null;
          eval("column = " + export_config.columnJs);
          console.log(column)
          let export_data = LAY_EXCEL.filterExportData(items, column);
          let sheet_data = new Object();
          eval("sheet_data." + res.data.sheet + "=export_data;");
          let cellPos = this.createCellPos(parseInt(export_config.columnCount) - 1);

          LAY_EXCEL.setExportCellStyle(export_data, "A1:" + cellPos + "1", {
            s: {
              fill: { fgColor: { rgb: "FFFF00" } },
              alignment: {
                horizontal: 'center',
                vertical: 'center'
              },
              font: {
                sz: 12,
                bold: true
              }
            }
          });

          LAY_EXCEL.exportExcel(sheet_data, res.data.fileName, 'xlsx', {
            extend: {
              '!merges': export_config.mergeCells,
              '!cols': export_config.width,
              '!rows': LAY_EXCEL.makeRowConfig({
                1: 40
              })
            }
          });
        } else {
          this.$message.error("导出数据为空");
        }
      }).catch((err) => {
        console.log(err)
      })
    },
  }
};
</script>
